package com.twu.biblioteca.controller;

import com.twu.biblioteca.controller.Book;
import com.twu.biblioteca.controller.Movie;
import com.twu.biblioteca.model.BookDAO;
import com.twu.biblioteca.model.MovieDAO;
import com.twu.biblioteca.model.UserDAO;

import java.util.ArrayList;
import java.lang.Exception;

/**
 * Created by ggoulart on 9/18/14.
 */
public class Biblioteca {

    private BookDAO bookDAO = new BookDAO();
    private MovieDAO movieDAO = new MovieDAO();

    public ArrayList<Book> listBooks() {
        return bookDAO.getAvailableBooks();
    }

    public String checkoutBook(String bookName, String userLibraryNumber) {
        try {
            Book book = bookDAO.findBookByName(bookName);
            if(bookDAO.removeAvailableBook(book)) {
                UserDAO userDAO = new UserDAO();
                User user = userDAO.findUserByLibraryNumber(userLibraryNumber);
                bookDAO.addCheckoutBooks(book, user);
            } else
                throw new Exception();
            return "Thank you! Enjoy the book.";
        } catch (Exception e) {
            return "That book is not available.";
        }
    }

    public String returnBook(String bookName) {
        try {
            Book book = bookDAO.findBookByName(bookName);
            if(bookDAO.removeCheckoutBooks(book))
                bookDAO.addAvailableBook(book);
            else
                throw new Exception();
            return "Thank you for returning the book.";
        } catch (Exception e) {
            return "That is not a valid book to return.";
        }
    }

    public ArrayList<Movie> listMovies() {
       return movieDAO.getAvailableMovies();
    }

    public String checkoutMovie(String movieName, String userLibraryNumber) {
        try {
            Movie movie = movieDAO.findMovieByName(movieName);
            if(movieDAO.removeAvailableMovie(movie)) {
                UserDAO userDAO = new UserDAO();
                User user = userDAO.findUserByLibraryNumber(userLibraryNumber);
                movieDAO.addCheckoutMovie(movie, user);
            } else
                throw new Exception();
            return "Thank you! Enjoy the movie.";
        } catch (Exception e) {
            return "That movie is not available.";
        }
    }

    public String returnMovie(String movieName) {
        try {
            Movie movie = movieDAO.findMovieByName(movieName);
            if(movieDAO.removeCheckoutMovie(movie))
                movieDAO.addAvailableMovie(movie);
            else
                throw new Exception();
            return "Thank you for returning the movie.";
        } catch (Exception e) {
            return "That is not a valid movie to return.";
        }
    }
}
